package course;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public  class LogonServlet extends HttpServlet{

	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
	throws ServletException, IOException {

    	HttpSession session = req.getSession();
    
		String loguser = req.getParameter("loguser");
		String logpwd = req.getParameter("logpwd");
//		String actloguser = null;
//		boolean status;
		String errorcode = null;
		
		PreparedStatement ps = null;
		Connection con = null;
		String checkuser = null; 
//		String checkpass = null;
		String checkvalid = null;
//		String checkactive = null;
//		String checkactivecode =null;
		
		try {
			con = DBcon.getConnection();
			System.out.println("connected!");
			ps = con.prepareStatement("select ur_id from tuser where ur_id = (?)");
		    ps.setString(1, loguser);
		    ResultSet rs = ps.executeQuery();
		    while (rs.next()){
		    	 checkuser = rs.getString(1);
			}
		    if (checkuser==null){
		    	System.out.println("no user");
		    	errorcode="LI-001";
				session.setAttribute("error", errorcode);
				resp.sendRedirect("logfail.jsp");
		    } else if (checkuser != null && logpwd != null){
		    	  ps = con.prepareStatement("select ur_priority from tuser where ur_id=(?) and ur_passwd = (?)");
				  ps.setString(1, loguser);
				  ps.setString(2, logpwd);
	    		  ResultSet rsb = ps.executeQuery();
	    		  while (rsb.next()){
		    			 checkvalid = rsb.getString(1);
		    			 System.out.println("CHECK VALID !" + checkvalid);	    			  
	    		  }
	    		  if (checkvalid == null){
	    			  System.out.println("Wrong password");
			    	  errorcode="LI-002";
					  session.setAttribute("error", errorcode);
					  resp.sendRedirect("logfail.jsp");
	    		  }else {
			    	  session.setAttribute("loguser", loguser);
			    	  session.setAttribute("logpwd", logpwd);
			    	  session.setAttribute("logprior", checkvalid);
	    		  	  resp.sendRedirect("menulogin.jsp");
		    		  System.out.println("SUCCESS !" + checkvalid);
			    	  }    	  
			    	  
		    }
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}			

	
		finally {
			try {

				ps.close();
				con.close();
			} catch (SQLException e) {
			// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}

	
